package cn.iocoder.yudao.module.trade.order.service.handler;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.module.api.promotion.discount.DiscountActivityApi;
import cn.iocoder.yudao.module.api.promotion.discount.dto.DiscountProductRespDTO;
import cn.iocoder.yudao.module.api.promotion.fod.FirstOrderDiscountApi;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderDO;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderItemDO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

/**
 * 首单优惠折扣的 {@link TradeOrderHandler} 实现类
 *
 * @author 山野羡民
 */
@Slf4j
@Component
public class TradeFirstOrderDiscountOrderHandler implements TradeOrderHandler {
    @Resource
    private DiscountActivityApi discountActivityApi;
    @Resource
    private FirstOrderDiscountApi firstOrderDiscountApi;

    @Override
    public void afterOrderCreate(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        // 排除未使用折扣的订单（非积分抵扣、联盟豆抵扣）
        if (order.getDiscountPrice() == null || order.getDiscountPrice() <= 0 || order.getDeductPoint() > 0 || order.getDeductCryptocurrency() > 0) {
            return;
        }
        // 排除限时折扣活动的订单
        List<DiscountProductRespDTO> discountProducts = discountActivityApi.getMatchDiscountProductListBySkuIds(
                convertSet(orderItems, TradeOrderItemDO::getSkuId));
        if (CollUtil.isNotEmpty(discountProducts)) {
            return;
        }
        log.debug("[afterOrderCreate][订单({}) 创建成功，享受了首单优惠折扣，减免了({}) 元]", order.getNo(), MoneyUtils.fenToYuanStr(order.getDiscountPrice()));
        firstOrderDiscountApi.applyPlatformDiscount(order.getUserId(), order.getNo(), order.getTotalPrice(), order.getDiscountPrice());
    }

}
